package com.ljs.module.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ftp.FtpException;
import cn.hutool.extra.ftp.FtpMode;
import com.ljs.module.common.PathEnum;
import com.ljs.module.entity.smartbi.SearchExt;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class FtpUtil {
    static String ip = "10.10.201.9";
    static Integer port = 21;
    static String user = "test";
    static String pwd = "smartbi";
    static String charset = "gbk";
    static String model = "Passive"; // Active Passive
    static Ftp ftp = null;

    public static Ftp init(){
        if (ftp == null) {
            ftp = new Ftp(ip, port, user, pwd, Charset.forName(charset));
            if (model.equals("Active")) {
                ftp.setMode(FtpMode.Active);
            } else {
                ftp.setMode(FtpMode.Passive);
            }
        }
        return ftp;
    }

    public static void close(){
        if (ftp != null) {
            try {
                ftp.close();
                ftp = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static List<String> cache(String[] baseUrls, String version, String branch){
        FileUtil.directoryNotExistThenMake(PathEnum.FTP.getPath() + File.separator + version);
        String cacheFilePath =  PathEnum.FTP.getPath() + File.separator + version + File.separator + branch + ".txt";
        FileUtil.fileNotExistThenMake(cacheFilePath);
        String basePath = "/";
        for (String baseUrl : baseUrls) {
            basePath += baseUrl + "/";
        }
        basePath += version + "/" + branch + "/";
        ftp.cd(basePath);
        List<String> ftpFileNames = new ArrayList<>();
        List<String> ftpFiles = ftp.ls(basePath);
        for (String ftpFile : ftpFiles) {
            String finalBasePath = basePath;
            List<String> projects = ftp.ls(basePath + ftpFile)
                    .stream().filter(x -> !x.equals("master"))
                    .map(x -> finalBasePath + ftpFile + "/" + x)
                    .collect(Collectors.toList());
            if (projects != null && projects.size() > 0) {
                ftpFileNames.addAll(projects);
            }
        }
        FileUtil.changeExtList(cacheFilePath, ftpFileNames, x -> x);
        return ftpFileNames;
    }

    public static List<String> loadCache(String version, String branch){
        FileUtil.directoryNotExistThenMake(PathEnum.FTP.getPath() + File.separator + version);
        String cacheFilePath =  PathEnum.FTP.getPath() + File.separator + version + File.separator + branch  + ".txt";
        FileUtil.fileNotExistThenMake(cacheFilePath);
        List<String> cacheNames = FileUtil.loadExtList(cacheFilePath, Collectors.toList(), x->x);
        return cacheNames;
    }

    public static Map<String, SearchExt> searchExt(List<String> list, String searchExt, String[] extensionsExt) {
        Map<String, Boolean> extensionsExtMap = Arrays.stream(extensionsExt).collect(Collectors.toMap(k -> k, v -> true, (v1,v2)->v1));
        return list.stream()
                .filter(x -> {
                    String name = x.substring(x.lastIndexOf("/") + 1);
                    return  (extensionsExtMap.size() > 0 && extensionsExtMap.get(name) != null)
                            || (!StringUtils.isBlank(searchExt) && name.toLowerCase().contains(searchExt.toLowerCase()));
                }).map(x -> {
                    String name = x.substring(x.lastIndexOf("/") + 1);
                    List<String> paths = ftp.ls(x + "/master").stream()
                            .sorted(Comparator.comparingLong(y -> Long.parseLong(y.toString())).reversed())
                            .limit(5).collect(Collectors.toList());
                    SearchExt searchExtRepo = new SearchExt().setFtpPath(x + "/master").setName(name).setPaths(paths);
                    if (searchExtRepo.getPaths() != null && searchExtRepo.getPaths().size() > 0) {
                        searchExtRepo.setSelect(searchExtRepo.getPaths().get(0));
                    }
                    return searchExtRepo;
                }).collect(Collectors.toMap(SearchExt::getName, y -> y,(v1,v2)->v1));
    }

    public static boolean exist(String ftpPath,Ftp ftp){
        String fileName = cn.hutool.core.io.FileUtil.getName(ftpPath);
        String dir = StrUtil.removeSuffix(ftpPath, fileName);

        List names;
        try {
            names = ftp.ls(dir);
        } catch (FtpException var6) {
            return false;
        }

        if (CollUtil.isEmpty(names)) {
            return false;
        } else if (StrUtil.isEmpty(fileName)) {
            return false;
        } else {
            Iterator var2 = names.iterator();

            String name;
            do {
                if (!var2.hasNext()) {
                    return false;
                }

                name = (String)var2.next();
            } while(!fileName.equals(name));

            return true;
        }
    }
}
